﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using XUnity.AutoTranslator.Plugin.Core.Configuration;
using XUnity.AutoTranslator.Plugin.Core.Utilities;
using XUnity.Common.Logging;

namespace XUnity.AutoTranslator.Plugin.Core
{
   internal static class SettingsTranslationsInitializer
   {
      private static readonly char[] TranslationSplitters = new char[] { '=' };

      public static void LoadTranslations()
      {
         Settings.Replacements.Clear();
         Settings.Preprocessors.Clear();

         Directory.CreateDirectory( Settings.TranslationsPath );
         var substitutionFile = new FileInfo( Settings.SubstitutionFilePath ).FullName;
         var preprocessorsFile = new FileInfo( Settings.PreprocessorsFilePath ).FullName;

         LoadTranslationsInFile( substitutionFile, true, false );
         LoadTranslationsInFile( preprocessorsFile, false, true );
      }

      private static void LoadTranslationsInFile( string fullFileName, bool isSubstitutionFile, bool isPreprocessorFile )
      {
         var fileExists = File.Exists( fullFileName );
         if( fileExists || isSubstitutionFile || isPreprocessorFile )
         {
            if( fileExists )
            {
               using( var stream = File.OpenRead( fullFileName ) )
               {
                     LoadTranslationsInStream( stream, fullFileName, isSubstitutionFile, isPreprocessorFile );
               }
            }
            else if( isSubstitutionFile || isPreprocessorFile )
            {
               var fi = new FileInfo( fullFileName );
               Directory.CreateDirectory( fi.Directory.FullName );

               using( var stream = File.Create( fullFileName ) )
               {
                  stream.Write( new byte[] { 0xEF, 0xBB, 0xBF }, 0, 3 ); // UTF-8 BOM
                  stream.Close();
               }
            }
         }
      }

      private static void LoadTranslationsInStream( Stream stream, string fullFileName, bool isSubstitutionFile, bool isPreprocessorFile )
      {
         if( !Settings.EnableSilentMode ) XuaLogger.AutoTranslator.Debug( $"Loading texts: {fullFileName}." );

         var reader = new StreamReader( stream, Encoding.UTF8 );
         {
            var context = new TranslationFileLoadingContext();
            var set = new HashSet<string>();

            string[] translations = reader.ReadToEnd().Split( new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries );
            foreach( string translatioOrDirective in translations )
            {
               if( context.IsExecutable( Settings.ApplicationName ) )
               {
                  string[] kvp = translatioOrDirective.Split( TranslationSplitters, StringSplitOptions.None );
                  if( kvp.Length == 2 )
                  {
                     string key = TextHelper.Decode( kvp[ 0 ] );
                     string value = TextHelper.Decode( kvp[ 1 ] );

                     if( !string.IsNullOrEmpty( key ) && !string.IsNullOrEmpty( value ) )
                     {
                        if( isSubstitutionFile )
                        {
                           Settings.Replacements[ key ] = value;
                        }
                        else if( isPreprocessorFile )
                        {
                           Settings.Preprocessors[ key ] = value;
                        }
                     }
                  }
               }
            }
         }
      }
   }
}
